package com.sctvcloud.weiyuan.ui.activities;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;

import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.gson.Gson;
import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.dialog.ShareFragment;
import com.ruihang.generalibrary.ui.widget.CustomEXImageView;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.sctvcloud.weiyuan.R;
import com.sctvcloud.weiyuan.base.BaseActivity;
import com.sctvcloud.weiyuan.base.BaseDetailActivity;
import com.sctvcloud.weiyuan.beans.FNews;
import com.sctvcloud.weiyuan.beans.JSBeans;
import com.sctvcloud.weiyuan.beans.WmJSBean;
import com.sctvcloud.weiyuan.ui.fragment.CivilizedPracticeFragment;
import com.sctvcloud.weiyuan.ui.fragment.ColumnBaseFragment;
import com.sctvcloud.weiyuan.ui.fragment.MyPlatFormFragment;
import com.sctvcloud.weiyuan.ui.utils.GlideCircleTransform;
import com.sctvcloud.weiyuan.ui.utils.GlideUtil;
import com.sctvcloud.weiyuan.utils.UserManager;

import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 文明实践
 */
public class WenMingActivity extends BaseDetailActivity {
    @BindView(R.id.title_top_logo_layout)
    protected LinearLayout title_top_logo_layout;
    @BindView(R.id.title_top_title)
    protected CustomFontTextView title_top_title;
    @BindView(R.id.title_top_layout_edit)
    protected CustomFontTextView share;
    private static final String BASE_URL = "http://wmsj.scwy.tv:8081/dist/#/home";
    private static final int REQUEST_CODE_LOGIN = 111;
    private WebView mWebView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wen_ming_shi_jian);
        ButterKnife.bind(this);
        initViews();

    }


    private void initViews() {
        title_top_logo_layout.setVisibility(View.GONE);
        title_top_title.setVisibility(View.VISIBLE);
        title_top_title.setText("文明实践");
        share.setVisibility(View.GONE);
        mWebView = (WebView) findViewById(R.id.webView);
        initSettings();

        if (UserManager.getInstance().isLogin() && null != UserManager.getInstance().getUser()) {
            String url = BASE_URL + "?utk=" + UserManager.getInstance().getUser().getToken();
            mWebView.loadUrl(url);
        } else {
            String url = BASE_URL;
            mWebView.loadUrl(url);
        }
        mWebView.setWebViewClient(new WebViewClient() {
            /**
             * 防止加载网页时调起系统浏览器
             */
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (!url.startsWith("http://") && !url.startsWith("https://")) {
                    return true;
                }
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                String titleStr = view.getTitle();
//                if (!TextUtils.isEmpty(titleStr)) {
////                    if (TextUtils.isEmpty(title)){
//                    title = titleStr;
////                    }
//                }
            }
        });
        mWebView.addJavascriptInterface(new Object() {
            @JavascriptInterface
            public void callRouter(String s1, String s2) {
                //H5页面调用Android原生代码
                if (!TextUtils.isEmpty(s1)) {
                    try {
                        JLog.e("htmlLogin", "-----------------------s1-" + s1 + "----s2" + s2);
                        if ("sharewmsj".equalsIgnoreCase(s2)) {
                            WmJSBean wnBean = new Gson().fromJson(s1, WmJSBean.class);
                            if (null != wnBean) {
                                toShare(wnBean.getUrl(), wnBean.getJson());
                            }
                        } else {
                            JSBeans jsonBean = new Gson().fromJson(s1, JSBeans.class);
                            parseJSMethod(jsonBean);
                        }
//                        String actId =
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

        }, "bridge");
    }

    /**
     * 回调的方法解析判断
     */
    private void parseJSMethod(JSBeans bean) {
        if (null != bean) {
            String method = bean.getMethod().trim();
            if ("Login".equalsIgnoreCase(method)) {
                //H5回调，判断是否已登录
                if (UserManager.isLoginS()) {
                    String token = UserManager.getInstance().getToken();
                    if (!TextUtils.isEmpty(token)) {
                        JLog.e("htmlLogin", "-------is login-----token = " + token);
                    } else {
                        toLogin();
                    }
                } else {
                    toLogin();
                }
            } else if ("Reg".equalsIgnoreCase(method)) {
//             toLogin();
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_LOGIN) {
            if (resultCode == LoginActivity.RESULT_OK) {
                if (UserManager.getInstance().isLogin() && null != UserManager.getInstance().getUser()) {
                    String url = BASE_URL + "?utk=" + UserManager.getInstance().getUser().getToken();
                    mWebView.loadUrl(url);
                } else {
                    String url = BASE_URL;
                    mWebView.loadUrl(url);
                }
            }
        }
    }

    @SuppressLint("SetJavaScriptEnabled")
    private void initSettings() {
        WebSettings webSetting = mWebView.getSettings();
        String ua = webSetting.getUserAgentString();
        webSetting.setUserAgentString(ua + " SCGC_UA");
        webSetting.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSetting.setAllowFileAccess(true);
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSetting.setSupportZoom(false);
        webSetting.setBuiltInZoomControls(false);
        webSetting.setUseWideViewPort(true);
        webSetting.setSupportMultipleWindows(false);
        // webSetting.setLoadWithOverviewMode(true);
        webSetting.setAppCacheEnabled(true);
        // webSetting.setDatabaseEnabled(true);
        webSetting.setDomStorageEnabled(true);
        webSetting.setJavaScriptEnabled(true);
        webSetting.setGeolocationEnabled(true);
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
        webSetting.setAppCachePath(this.getDir("appcache", 0).getPath());
        webSetting.setDatabasePath(this.getDir("databases", 0).getPath());
        webSetting.setGeolocationDatabasePath(this.getDir("geolocation", 0)
                .getPath());
        // webSetting.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);
        webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            webSetting.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        mWebView.setWebChromeClient(new WebChromeClient());
        mWebView.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });
    }


    @OnClick(value = {R.id.title_top_layout_back})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.title_top_layout_back:
                onBackPressed();
                break;
        }
    }

    private void toShare(String url, String title) {
        if (!TextUtils.isEmpty(url)) {
            FNews item = new FNews();
            item.setNewsShareUrl(url);
            if (TextUtils.isEmpty(title)) {
                item.setNewsTitle("文明实践");
            } else {
                item.setNewsTitle(title);
            }
//                    this.setNewsId(item.getNewsId());
            showShareFragment(item, new ShareFragment.OnShareFragmentClickListener() {
                @Override
                public void onClick(Pair<String, String> pairs) {
                }
            });
        } else {
            toast(R.string.share_data_wrong);
        }
    }
}
